package org.suyafei.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.suyafei.component.SmsComponent;
import org.suyafei.config.SmsConfig;
import org.suyafei.constant.RedisKey;
import org.suyafei.enums.BizCodeEnum;
import org.suyafei.enums.SendCodeEnum;
import org.suyafei.service.NotifyService;
import org.suyafei.utils.CheckUtil;
import org.suyafei.utils.CommonUtil;
import org.suyafei.utils.JsonData;

import java.util.concurrent.TimeUnit;


/**
 * @author 宿某人
 * @Date: 2021/12/09/11:13 上午
 * @Description:
 */
@Slf4j
@Service
public class NotifyServiceImpl implements NotifyService {


    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private SmsComponent smsComponent;

    @Autowired
    private SmsConfig smsConfig;

    /**
     * 手机验证码的发送间隔时间
     */
    private static final long LEFT_TIME = 1000 * 60;

    @Override
    public JsonData sendCode(SendCodeEnum sendCodeEnum, String to) {

        String cacheKey = String.format(RedisKey.CHECK_CODE_KEY, sendCodeEnum.name(), to);

        String cacheValue = redisTemplate.opsForValue().get(cacheKey);
        //如果不为空，在判断是否是流失秒内重复发送
        if (StringUtils.isNotBlank(cacheValue)) {
            long ttl = Long.parseLong(cacheValue.split("_")[1]);
            //当前时间戳减去验证码发送的时间戳，如果小于60秒，则不给重复发送
            long leftTime = CommonUtil.getCurrentTimestamp() - ttl;
            if (leftTime < LEFT_TIME) {
                log.info("重复发送短信验证码，时间间隔：{}", leftTime);
                return JsonData.buildResult(BizCodeEnum.CODE_LIMITED);
            }

        }

        String code = CommonUtil.getRandomCode(4);

        String value = code + "_" + CommonUtil.getCurrentTimestamp();

        redisTemplate.opsForValue().set(cacheKey, value, LEFT_TIME, TimeUnit.MILLISECONDS);

        if (CheckUtil.isEmail(to)) {
            //发送邮箱验证码 TODO

        } else if (CheckUtil.isPhone(to)) {
            //发送手机验证码
            smsComponent.send(to, smsConfig.getTemplateId(), code);
        }
        return JsonData.buildSuccess();
    }

    /**
     * 验证手机验证码
     * @param sendCodeEnum
     * @param to
     * @param code
     * @return
     */
    @Override
    public boolean checkCode(SendCodeEnum sendCodeEnum, String to, String code) {
        String cacheKey = String.format(RedisKey.CHECK_CODE_KEY, sendCodeEnum.name(), to);

        String cacheValue = redisTemplate.opsForValue().get(cacheKey);
        if (StringUtils.isNotBlank(cacheValue)) {
            String cacheCode = cacheValue.split("_")[0];
            if (cacheCode.equalsIgnoreCase(code)) {
                //删除验证
                redisTemplate.delete(cacheKey);
                return true;
            }
        }
        return false;
    }


}
